package thread.multi;

public class UnsafeBank {

    public static void main(String[] args) {
        //账户设置
        Account account = new Account(1000,"后宫基金");

        Drawing you = new Drawing(account, 50, "后宫王");
        Drawing girl1 = new Drawing(account, 10, "淘气妹妹");
        Drawing girl2 = new Drawing(account, 100, "安静姐姐");

        you.start();
        girl1.start();
        girl2.start();
    }
}

//银行账户
class Account {
    private int money;
    private String name;

    public Account(int money,String name) {
        this.money = money;
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

//取钱操作
class Drawing extends Thread {
    //账户
    private Account account;
    //余额
    private int valance;
    //花费
    private int cost;



    public Drawing(Account account,int valance,int cost) {
        this.account = account;
        this.valance = valance;
        this.cost = cost;
    }

    public Drawing(Account account,int cost,String name) {
        this.account = account;
        this.cost = cost;
        super.setName(name);
    }

    //取钱操作
    //增加同步机制，synchronized默认锁的是this
    @Override
    public synchronized void run() {

        //锁的对象是变化的量，需要增删改的量
        synchronized (account) {
            //判断，余额不足，不可取钱
            if (account.getMoney() - cost < 0) {
                System.out.println(Thread.currentThread().getName()+"余额不足！");
                return ;
            }

            //sleep()问题放大
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //余额计算，并重写账户钱
            valance = account.getMoney() - cost;
            account.setMoney(valance);

            System.out.println(account.getName()+"账户余额为："+account.getMoney());
            //函数操作数据一致
            //this.getName() = Thread.currentThread().getName()
            System.out.println(this.getName()+"花费"+cost);

        }
      }
}